package repository

import (
	"context"
	"database/sql"
	"strings"

	"mall/common/modelx"
	"mall/service/backend/model"

	"github.com/volatiletech/sqlboiler/v4/boil"
	"github.com/volatiletech/sqlboiler/v4/queries/qm"
	"github.com/zeromicro/go-zero/core/stores/cache"
)

type (
	// MemberLevelRepository is an interface to be customized, add more methods here,
	// and implement the added methods in customMemberLevelRepository.
	MemberLevelRepository interface {
		Conn() error
		FindOne(ctx context.Context, id int64, cols []string) (*model.MemberLevel, error)
		GetList(
			ctx context.Context,
			cols model.M,
			withCount int,
			filter map[string]map[string][]any,
		) ([]*model.MemberLevel, int64, error)
		Insert(ctx context.Context, ml *model.MemberLevel) error
		Update(ctx context.Context, ml *model.MemberLevel) (int64, error)
		UpdateBatch(ctx context.Context, ids []uint64, cols model.M) (int64, error)
		ForceDeleteBatch(ctx context.Context, ids []uint64) (int64, error)
	}

	customMemberLevelRepository struct {
		cacheConf  cache.CacheConf
		dataSource string

		mysqlConn *sql.DB
	}

	// Custom struct for selecting a subset of data
	RandomInfo struct {
		MaxId int     `boil:"max_id"`
		MinId int     `boil:"min_id"`
		Rand  float64 `boil:"rand"`
	}
)

// NewMemberLevelRepository returns a repository for the database table.
func NewMemberLevelRepository(dataSource string, cacheConf cache.CacheConf) MemberLevelRepository {
	return &customMemberLevelRepository{
		cacheConf:  cacheConf,
		dataSource: dataSource,
	}
}

func (r *customMemberLevelRepository) Conn() error {
	if r.mysqlConn == nil {
		mysqlConn, err := modelx.NewMysqlConn(r.dataSource)
		if err != nil {
			return err
		}

		r.mysqlConn = mysqlConn
	}

	return nil
}

func (r *customMemberLevelRepository) FindOne(
	ctx context.Context,
	id int64,
	cols []string,
) (ml *model.MemberLevel, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	ml, err = model.FindMemberLevel(ctx, r.mysqlConn, uint64(id), cols...)
	if err == sql.ErrNoRows {
		return nil, model.ErrNotFound
	}

	return
}

func (r *customMemberLevelRepository) GetList(
	ctx context.Context,
	cols model.M,
	withCount int,
	filter map[string]map[string][]any,
) (list []*model.MemberLevel, count int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	var mods []qm.QueryMod
	var page int
	var pageSize int
	var offset int
	var limit int
	var selectCol string
	for k, v := range cols {
		switch k {
		case "page":
			if val, ok := v.(int64); ok && val > 1 {
				page = int(val)
			}
		case "pageSize":
			if val, ok := v.(int64); ok && val > 0 {
				pageSize = int(val)
			}
		case "offset":
			if val, ok := v.(int32); ok && val > 0 {
				offset = int(val)
			}
		case "limit":
			if val, ok := v.(int32); ok && val > 0 {
				limit = int(val)
			}
		case "orderBy":
			if val, ok := v.(string); ok && val != "" {
				mods = append(mods, qm.OrderBy(val))
			}
		case "select":
			if val, ok := v.(string); ok && val != "" {
				selectCol = val
			}
		}
	}

	if filter != nil {
		for key, opMap := range filter {
			switch key {
			case model.MemberLevelColumns.MemberLevelID:
				mods = append(mods, modelx.GetIntMods(model.MemberLevelColumns.MemberLevelID, opMap)...)
			case model.MemberLevelColumns.Name:
				mods = append(mods, modelx.GetStringMods(model.MemberLevelColumns.Name, opMap)...)
			case model.MemberLevelColumns.Slug:
				mods = append(mods, modelx.GetStringMods(model.MemberLevelColumns.Slug, opMap)...)
			case model.MemberLevelColumns.IsDefault:
				mods = append(mods, modelx.GetBooleanMods(model.MemberLevelColumns.IsDefault, opMap)...)
			}
		}
	}

	if withCount >= 0 {
		if withCount >= 2 {
			var nextCount int64
			var previousCount int64
			subMods := make([]qm.QueryMod, len(mods), len(mods) + 3)
			copy(subMods, mods)
			subMods = append(subMods, qm.Limit(1))
			subMods = append(subMods, qm.Select(model.MemberLevelColumns.MemberLevelID))

			if withCount != 3 && offset >= 1 {
				subMods = append(subMods, qm.Offset(offset - 1))
				previousList, previousErr := model.MemberLevels(subMods...).All(ctx, r.mysqlConn)
				if previousErr != nil {
					err = previousErr
					return
				}
				if len(previousList) > 0 {
					previousCount = 1
				}
			}
			if limit > 0 {
				subMods = append(subMods, qm.Offset(offset + limit))
				nextList, nextErr := model.MemberLevels(subMods...).All(ctx, r.mysqlConn)
				if nextErr != nil {
					err = nextErr
					return
				}
				if len(nextList) > 0 {
					nextCount = 1
				}
			}

			count = previousCount + nextCount * 2
		} else {
			count, err = model.MemberLevels(mods...).Count(ctx, r.mysqlConn)
			if err != nil {
				return
			}

			if withCount == 0 {
				return
			}
		}
	}

	if pageSize > 0 {
		if page > 1 {
			mods = append(mods, qm.Offset(pageSize*(page-1)))
		}
		mods = append(mods, qm.Limit(pageSize))
	} else if limit > 0 || offset > 0 {
		if limit > 0 {
			mods = append(mods, qm.Limit(limit))
		}
		if offset > 0 {
			mods = append(mods, qm.Offset(offset))
		}
	}

	var columns []string
	if selectCol != "" {
		if selectCol != "," {
			columns = strings.Split(selectCol, ",")
		}
		columns = append(columns, model.MemberLevelColumns.MemberLevelID)
	}
	if len(columns) > 0 {
		mods = append(mods, qm.Select(columns...))
	}

	list, err = model.MemberLevels(mods...).All(ctx, r.mysqlConn)
	return
}

func (r *customMemberLevelRepository) Insert(
	ctx context.Context,
	ml *model.MemberLevel,
) error {
	if err := r.Conn(); err != nil {
		return err
	}

	return ml.Insert(ctx, r.mysqlConn, boil.Infer())
}

func (r *customMemberLevelRepository) Update(
	ctx context.Context,
	ml *model.MemberLevel,
) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return 0, err
	}

	rowsAff, err = ml.Update(ctx, r.mysqlConn, boil.Blacklist(
		model.MemberLevelColumns.MemberLevelID,
	))
	return
}

func (r *customMemberLevelRepository) UpdateBatch(
	ctx context.Context,
	ids []uint64,
	cols model.M,
) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	if len(ids) > 0 {
		var mods []qm.QueryMod
		mods = append(mods, model.MemberLevelWhere.MemberLevelID.IN(ids))
		rowsAff, err = model.MemberLevels(mods...).UpdateAll(ctx, r.mysqlConn, cols)
	}

	return
}

func (r *customMemberLevelRepository) ForceDeleteBatch(ctx context.Context, ids []uint64) (rowsAff int64, err error) {
	if err = r.Conn(); err != nil {
		return
	}

	if len(ids) > 0 {
		var mods []qm.QueryMod
		mods = append(mods, model.MemberLevelWhere.MemberLevelID.IN(ids))
		rowsAff, err = model.MemberLevels(mods...).DeleteAll(ctx, r.mysqlConn)
	}

	return
}
